package other.edan.pass;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.api.annotations.RestQueryParam;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEvent;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventRequest;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventResponse;
import com.rkhd.platform.sdk.data.model.DelApplyForDetails__c;
import com.rkhd.platform.sdk.data.model.DelApplyFor__c;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.exception.XsyHttpException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import other.edan.pass.utils.ComUtils;
import other.edan.pass.utils.HCXObjectService;
import other.edan.pass.utils.TfReturnMsgTools;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**功能描述：删除申请审批通过后 ，作废相关的单据
 * @ClassName: DelApplyForApproval
 * @Description:
 * @author 范伟绵
 * @date 2024年07月01日
 */

@RestApi(baseUrl = "/xsy/edan")
public class DelApplyForApproval implements ApprovalEvent {
	private final static Logger LOGGER = LoggerFactory.getLogger();
	private final static String LOG_MSG_EX="删除申请审批通过后 ，作废相关的单据:";

	//删除申请业务类型 对应 APIKEY
	private final static Map<Long,String> entityApiKeyMap=new HashMap<>();
	private final static Long campaign_ENTITY=3361183033203290L;				//市场活动
	private final static Long medicalArchives_ENTITY=3361207076330115L;     	//专家
	private final static Long competitors_ENTITY=3361207076330116L;				//竞争对手
	private final static Long account_ENTITY=3361196289350246L;					//客户
	private final static Long contact_ENTITY=3361206061488727L;					//联系人
	private final static Long lead_ENTITY=3361199490947733L;					//销售线索
	private final static Long opportunity_ENTITY=3361196289350247L;				//销售机会
	
	public ApprovalEventResponse execute(ApprovalEventRequest request) throws ScriptBusinessException {
		Long id = request.getDataId();
		request.getEntityApiKey();
		LOGGER.info(LOG_MSG_EX + "开始，数据ID:"+id);
		
		ApprovalEventResponse response = new ApprovalEventResponse();
		try {
			response= patchUpdate(id);
		} catch (Exception e) {
			response= TfReturnMsgTools.getApprResponse(false, LOG_MSG_EX + "失败.");
			LOGGER.error(LOG_MSG_EX +"发生异常"+e.getMessage());
			return response;
		}
		LOGGER.info(LOG_MSG_EX + "结束");
		return response;
	}
	
	@RestMapping(value = "/cancelDocument", method = RequestMethod.POST)
	public String cancelDocument(@RestQueryParam(name="id") String id)  {
		LOGGER.info(LOG_MSG_EX+"执行了按钮事件");
		try{
			ApprovalEventResponse response= patchUpdate(Long.valueOf(id));
			return TfReturnMsgTools.getJsonResult(response.getSuccess(),response.getMsg());
		}catch (Exception e){
			LOGGER.error("作废【单据】发送异常:"+e.getMessage());
			return TfReturnMsgTools.getExceptionResult("作废【单据】失败，请联系管理员！");
		}
	}
	
	/*功能描述：批量作废单据
	 * id：单据ID
	 */
	@SuppressWarnings("unchecked")
	public ApprovalEventResponse patchUpdate(Long id) throws ApiEntityServiceException, IOException, XsyHttpException {
		entityApiKeyMap.put(campaign_ENTITY,"campaign");					//市场活动
		entityApiKeyMap.put(medicalArchives_ENTITY,"medicalArchives__c");	//专家
		entityApiKeyMap.put(competitors_ENTITY,"competitors__c");			//竞争对手
		entityApiKeyMap.put(account_ENTITY,"account");						//客户
		entityApiKeyMap.put(contact_ENTITY,"contact");						//联系人
		entityApiKeyMap.put(lead_ENTITY,"lead");							//销售线索
		entityApiKeyMap.put(opportunity_ENTITY,"opportunity");				//销售机会

		HCXObjectService hcxObjectService=new HCXObjectService();
		Long delApplyForId=id;										//删除申请ID
		String returnMsgString= "获取【删除申请】信息失败";
		
		//获取【删除申请】信息
		DelApplyFor__c delApplyFor=new DelApplyFor__c();
		delApplyFor.setId(delApplyForId);
		delApplyFor=hcxObjectService.get(delApplyFor);
		if(null==delApplyFor) {
			LOGGER.error(returnMsgString);
			return TfReturnMsgTools.getApprResponse(false, returnMsgString);
		}
		LOGGER.info("【删除申请】信息:"+delApplyFor.toString());

		//获取【删除内容】信息
		String sqlString="Select marketing__c,account__c,expert__c,competitor__c,contacts__c,clue__c,opportunities__c,remark__c "
				+ " from delApplyForDetails__c where delApplyFor__c="+id;
		List<DelApplyForDetails__c> delApplyForDetailsList=HCXObjectService.queryAll(sqlString);
		if(delApplyForDetailsList.size()<=0) {
			//没有明细，不需要修改明细
			LOGGER.info("没有获取到【删除内容】信息");
			return TfReturnMsgTools.getApprResponse(false, "作废【单据】失败.");
		}
		LOGGER.info("【删除内容】信息:"+delApplyForDetailsList.toString());

		String apiKey=entityApiKeyMap.get(delApplyFor.getEntityType());
		JSONObject updateParam=generateParam(delApplyFor,delApplyForDetailsList);

		Boolean updateResult=ComUtils.patchUpdate(apiKey,updateParam);
		if(!updateResult){
			LOGGER.info("作废【单据】失败");
			return TfReturnMsgTools.getApprResponse(false, "作废【单据】失败.");
		}
		LOGGER.info("作废【单据】成功。");
		returnMsgString=(updateResult) ? "作废【单据】成功.":"作废【单据】失败.";

		//作废费控的市场活动申请
		if(delApplyFor.getEntityType().equals(campaign_ENTITY)){
			StringBuilder ids=new StringBuilder();
			for(DelApplyForDetails__c details:delApplyForDetailsList){
				ids.append(details.getMarketing__c()).append(",");
			}
			String param=ids.substring(0,ids.length()-1);
			LOGGER.info("作废市场活动ID列表:"+param);
			updateResult=ComUtils.patchCancelCampaign(param);
			returnMsgString=(updateResult) ? "作废【费控对应的市场活动申请】成功.":"作废【费控对应的市场活动申请】失败.";
		}

		LOGGER.info("patchUpdate 结束,"+returnMsgString);
		return TfReturnMsgTools.getApprResponse(updateResult, returnMsgString);
	}

	//功能描述：构建批量更新的参数
	private JSONObject generateParam(DelApplyFor__c delApplyFor,List<DelApplyForDetails__c> delApplyForDetailsList)
			throws ApiEntityServiceException {
		JSONObject batchData=new JSONObject();
		JSONArray dataArray=new JSONArray();
		Long entityType=delApplyFor.getEntityType();
		for(DelApplyForDetails__c details:delApplyForDetailsList){
			JSONObject tmpJson=new JSONObject();
			if(entityType.equals(campaign_ENTITY)){
				tmpJson.put("id",details.getMarketing__c());
			}else if(entityType.equals(medicalArchives_ENTITY)){
				tmpJson.put("id",details.getExpert__c());
			} else if(entityType.equals(competitors_ENTITY)){
				tmpJson.put("id",details.getCompetitor__c());
			}else if(entityType.equals(account_ENTITY)){
				tmpJson.put("id",details.getAccount__c());
			}else if(entityType.equals(contact_ENTITY)){
				tmpJson.put("id",details.getContacts__c());
			}else if(entityType.equals(lead_ENTITY)){
				tmpJson.put("id",details.getClue__c());
			}else if(entityType.equals(opportunity_ENTITY)){
				tmpJson.put("id",details.getOpportunities__c());
			}
			tmpJson.put("dataStatus__c",2);
			tmpJson.put("comment",(null==details.getRemark__c())?"":details.getRemark__c());

			JSONObject dataJson=new JSONObject();
			dataJson.put("data",tmpJson);

			dataArray.add(dataJson);
		}
		batchData.put("batchData",dataArray);

		LOGGER.info("参数:"+batchData.toJSONString());

		return batchData;
	}

	public static void main(String[] args) throws IOException, ApiEntityServiceException, XsyHttpException {
		DelApplyForApproval api=new DelApplyForApproval();
		api.patchUpdate(3362519616821858L);
	}
}